// 导入需要的three.js组件
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// 定义全局变量
let camera, scene, renderer;

// 初始化
function init() {
    const container = document.createElement('div');
    document.body.append(container);

    // camera
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 20);
    camera.position.set(-1.8, 0.6, 2.7);

    // scene
    scene = new THREE.Scene();

    // renderer
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1;
    container.appendChild(renderer.domElement);

    // controls
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.addEventListener('change', render);
    controls.minDistance = 2;
    controls.maxDistance = 10;
    controls.target.set(0, 0, - 0.2);
    controls.update();
}

// 加载模型的函数
async function load() {
    // load background texture
    const background_loader = new RGBELoader();
    const texture = await background_loader.loadAsync('https://threejs.org/examples/textures/equirectangular/royal_esplanade_1k.hdr');

    // set background
    texture.mapping = THREE.EquirectangularReflectionMapping;
    scene.background = texture;
    scene.environment = texture;

    // render background
    render();

    // load model
    const loader = new GLTFLoader();//.setPath('./');//.setPath('models/gltf/DamagedHelmet/glTF/');
    const gltf = await loader.loadAsync('https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf');

    // compile model
    const model = gltf.scene;
    await renderer.compileAsync(model, camera, scene);
    // add model to scene
    scene.add(model);

    // render model
    render();
}

// 执行渲染的函数
function render() {
    renderer.render(scene, camera);
}


// 启动
init();
load();
